import { useUserStore } from "../stores/user";
import { toast } from "../utils/index.js";
import { anyObject } from "../types/index.js"

let loading : number = 0;

const fetch = (
	url : string,
	method : "POST" | "GET",
	data : anyObject = {}
) : Promise<any> => {
	if ((url == '/NovelDetails/bakchapter_findispay') || (url == '/recharge/ttlist') || (url == '/NovelDetails/chapter_findunlock')) {

	} else {
		// if (loading === 0) {
		// 	uni.showLoading({
		// 		title: "加载中",
		// 		mask: true,
		// 	});
		// 	loading++;
		// }

	}
	return new Promise((resolve, reject) => {
		const userStore = useUserStore();
		uni.request({
		 url: `${process.env.VUE_APP_BASE_URL}${url}`,
			//url: `https://www.weiyue9.com/api${url}`,
			method,
			data,
			dataType: "json",
			header: {
				"content-type": "application/x-www-form-urlencoded",
				token: userStore.loginInfo?.token || "",
			},
			success(res : UniApp.RequestSuccessCallbackResult) {
				if (res.statusCode == 200) {
					resolve(res.data);
				} else if (res.statusCode == 401) {
					resolve({ code: 101 });
				} else {
					toast("网络错误");
					reject(res);
				}
			},
			fail(err) {
				toast("网络异常，请稍后重试！");
				reject(err);
			},
			complete() {
				if (loading > 0) {
					loading--;
				}
				if (url == '/NovelDetails/bakchapter_findispay') { loading = 0 }
				if (loading === 0) uni.hideLoading();
			},
		});
	});
};

export const GET = async (url : string, data : anyObject = {}) : Promise<any> => {
	return new Promise(async (resolve, reject) => {
		let res = await fetch(url, "GET", data);
		if (res.code == 200) {
			resolve(res.data);
		} else if (res.code == 101) {
			const userStore = useUserStore();
			userStore.Login(async () => {
				res = await fetch(url, "GET", data);
				if (res.code == 200) {
					resolve(res.data);
				} else {
					toast(res.message || "网络错误");
					reject(res);
				}
			});
		} else {
			toast(res.message || "网络错误");
			reject(res);
		}
	});
};

export const POST = async (url : string, data : anyObject = {}) : Promise<any> => {
	return new Promise(async (resolve, reject) => {
		let res = await fetch(url, "POST", data);
		if (res.code == 200) {
			resolve(res.data);
		} else if (res.code == 101) {
			const userStore = useUserStore();
			userStore.Login(async () => {
				res = await fetch(url, "POST", data);
				if (res.code == 200) {
					resolve(res.data);
				} else {
					toast(res.message || "网络错误");
					reject(res);
				}
			});
		} else {
			toast(res.message || "网络错误");
			reject(res);
		}
	})
};